 //
//  SaleApplyListVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "SaleApplyListVC.h"
#import "KwSegmentView.h"
#import "ActiveApplyCell.h"
#import "ActiviteDetailVC.h"
#import "ActiviteVerificationVC.h"
#import "ActiviteApplyVC.h"

#import "SAListModel.h"
#import "ProductDisplayListModel.h"
#import "EnterCostListModel.h"

#import "ProductDisplayDetailVC.h"
#import "PDCommitVC.h"

#import "EnterCostDetailVC.h"
#import "EnterCostCommitVC.h"

#import "OtherCostListModel.h"
#import "OtherCostDetailVC.h"
#import "OtherCostCommitVC.h"


#define Get_Module_type(A, B) _segCtr.selectedSegmentIndex == 0 ? A : B


@interface SaleApplyListVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UISegmentedControl *segCtr;

@property(nonatomic,assign) NSInteger moduleType;

//头部的条形title
@property(nonatomic,copy) NSArray *titleArr;

//当前选中的列表
@property (nonatomic,assign) NSInteger currtenNum;

@property (nonatomic,strong) UITableView *tableView;

//当前列表第几页
@property (nonatomic,assign) NSInteger currentPage;

//数据源
@property (nonatomic,strong) NSMutableArray *tableArray;

@property (nonatomic,strong) UIButton *confirmBtn;

@end

@implementation SaleApplyListVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    [self configRefreshControl];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNotification:) name:KwSegViewNotification object:nil];
    if (![Singleton shareInstance].noRefresh) {
        [self.tableView.mj_header beginRefreshing];
    }
    [Singleton shareInstance].noRefresh = NO;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Config UI
- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSegmentCtrWithArr:@[@"活动申请",@"活动核销"]];

    self.view.backgroundColor = [UIColor whiteColor];
    //创建顶部菜单
    KwSegmentView *segView =[[KwSegmentView alloc]initWithBtnNames:self.titleArr];
    segView.frame = CGRectMake(0, 0, self.view.width, 50);
    segView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segView];
    segView.cancleBlock = ^(){
        [self.view endEditing:YES];
    };

    //创建列表
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.estimatedRowHeight = 40.0;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(segView.mas_bottom);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency)
    {
        //创建底部按钮
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_confirmBtn setBackgroundColor:KwBlueColor];
        [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        switch (self.ApplyTypeNum) {
            case ApplyTypeEntryFeeApply: {
                [_confirmBtn setTitle:@"费用申请" forState:UIControlStateNormal];
            }
                break;

            case ApplyTypePromotionApply: {
                [_confirmBtn setTitle:@"申请活动" forState:UIControlStateNormal];
            }
                break;

            case ApplyTypeProductDisplayFeeApply: {
                [_confirmBtn setTitle:@"申请陈列费用" forState:UIControlStateNormal];
            }
                break;

            case ApplyTypeOtherFeeApply: {
                [_confirmBtn setTitle:@"费用申请" forState:UIControlStateNormal];
            }
                break;
            default:
                [_confirmBtn setTitle:@"申请活动" forState:UIControlStateNormal];
                break;
        }
        _confirmBtn.titleLabel.font = KwFont(16.0);
        [_confirmBtn addTarget:self action:@selector(startPlaceAnOrder) forControlEvents:UIControlEventTouchUpInside];
        _confirmBtn.layer.masksToBounds = YES;
        _confirmBtn.layer.cornerRadius = 5.0;
        [self.view addSubview:_confirmBtn];
        [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@-5);
            make.top.equalTo(_tableView.mas_bottom).offset(1);
            make.left.equalTo(@5);
            make.right.equalTo(@-5);
        }];
    }
    else
    {
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@0);
        }];
    }
}

- (void)createSegmentCtrWithArr:(NSArray *)arr
{
    _segCtr = [[UISegmentedControl alloc] initWithItems:arr];
    _segCtr.frame = CGRectMake(0, 0, 200, 30);
    _segCtr.tintColor = [UIColor whiteColor];
    _segCtr.selectedSegmentIndex = 0;
    [_segCtr addTarget:self action:@selector(changeList) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _segCtr;
}

- (void)configRefreshControl {
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf.tableView.mj_footer resetNoMoreData];
        [weakSelf loadingDataWithTag:1 showLoading:YES];
    }];
    [self.tableView.mj_header beginRefreshing];

    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadingDataWithTag:1 showLoading:YES];
    }];
}
#pragma mark - Load data


#pragma mark - Data request
- (void)loadingDataWithTag:(NSInteger)tag showLoading:(BOOL)isShowLoading
{
    __weak typeof(self) weakSelf = self;
    NWSaleApplyRequest *request = [[NWSaleApplyRequest alloc] init];
    switch (self.ApplyTypeNum) {
        case ApplyTypePromotionApply:
            self.moduleType = Get_Module_type(HomeModuleTypeSA, HomeModuleTypeSC);
            break;
        case ApplyTypeProductDisplayFeeApply:
            self.moduleType = Get_Module_type(HomeModuleTypePA, HomeModuleTypePC);
            break;
        case ApplyTypeEntryFeeApply:
            self.moduleType = Get_Module_type(HomeModuleTypeEA, HomeModuleTypeEC);
            break;
        case ApplyTypeOtherFeeApply:
            self.moduleType = Get_Module_type(HomeModuleTypeOA, HomeModuleTypeOC);
        default:
            break;
    }

    switch (_currtenNum)
    {
        case 0:
        {
            //全部
            [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:@"" approverUser:@"" approvalType:@"" moduleType:_moduleType];
        }
            break;
        case 1:
        {
            NSString *statusList = @"2,3,4";
            if (_moduleType == HomeModuleTypeSC || _moduleType == HomeModuleTypePC || _moduleType == HomeModuleTypeEC || _moduleType == HomeModuleTypeOC) {
                statusList = @"2,3,4,5";
            }

            //审批中
            [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:statusList approverUser:@"" approvalType:@"0" moduleType:_moduleType];
        }
            break;
        case 2:
        {

            UserModel *user = [UserModel getUser];
            if ([user.userType integerValue] == UserTypeAgency)
            {
                //已完成
                [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:[NSString stringWithFormat:@"%ld",(long)SAQueryStatusCompleted] approverUser:@"" approvalType:@"0" moduleType:_moduleType];
            }
            else
            {
                //待审批
                [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:@"" approverUser:[Singleton shareInstance].userId approvalType:@"0" moduleType:_moduleType];
            }

        }
            break;
        case 3:
        {
            UserModel *user = [UserModel getUser];
            if ([user.userType integerValue] == UserTypeAgency)
            {
                //已拒绝
                [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:@"" approverUser:@"" approvalType:@"1" moduleType:_moduleType];
            }
            else
            {
                //已完成
                [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:[NSString stringWithFormat:@"%ld",(long)SAQueryStatusCompleted] approverUser:@"" approvalType:@"0" moduleType:_moduleType];
            }

        }
            break;
        case 4:
        {
            //已拒绝
            [request startRequestGetAllApplyOrCheckListWithUserId:[Singleton shareInstance].userId pageNo:[NSString stringWithFormat:@"%ld",(long)_currentPage] pageSize:kPageSize approvalStatus:@"" approverUser:@"" approvalType:@"1" moduleType:_moduleType];
        }
            break;
        default:
            break;
    }

    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        [self stopRefresh];
        if (succ) {
            if (_currentPage == 1)
            {
                if (_tableArray == nil)
                {
                    _tableArray = [[NSMutableArray alloc] init];
                }else{
                    [_tableArray removeAllObjects];
                }
            }
            if (result && result != nil)
            {
                NSDictionary *dic;
                NSMutableArray *listArr;
                switch (self.moduleType) {
                    case HomeModuleTypeSA: {
                        dic = result[@"promotionAList"];
                        listArr = [SAListModel arrayOfModelsFromDictionaries:dic[@"list"]];
                    }
                        break;
                    case HomeModuleTypeSC: {
                        dic = result[@"PromotionEList"];
                        listArr = [SAListModel arrayOfModelsFromDictionaries:dic[@"list"]];
                    }
                        break;
                    case HomeModuleTypePA: {
                        dic = result[@"displayAList"];
                        listArr = [ProductDisplayListModel arrayOfModelsFromDictionaries:dic[@"list"]];
                    }
                        break;
                    case HomeModuleTypePC: {
                        dic = result[@"displayEList"];
                        listArr = [ProductDisplayListModel arrayOfModelsFromDictionaries:dic[@"list"]];
                    }
                        break;
                    case HomeModuleTypeEA:
                    case HomeModuleTypeEC: {
                        dic = result;
                        listArr = [EnterCostListModel arrayOfModelsFromDictionaries:result[@"data"]];
                    }
                        break;
                    case HomeModuleTypeOA:
                    case HomeModuleTypeOC: {
                        dic = result;
                        listArr = [OtherCostListModel arrayOfModelsFromDictionaries:result[@"data"]];
                    }
                        break;
                    default:
                        break;
                }

//                HomeModuleTypeSA = 0,//促销活动
//                HomeModuleTypeSC, // 促销活动核销
//                HomeModuleTypePA, //所有产品陈列申请
//                HomeModuleTypePC, //产品陈列核销
                
                if (self.moduleType == HomeModuleTypeSA || self.moduleType == HomeModuleTypeSC || self.moduleType == HomeModuleTypePA || self.moduleType == HomeModuleTypePC) {
                    if (listArr &&  [dic[@"pageNo"] integerValue] ==_currentPage)
                    {
                        _currentPage ++ ;//有下一页  show 加载按钮
                        [_tableArray addObjectsFromArray:listArr];
                        [_tableView reloadData];
                    }else
                    {
                        //没有下一页  hide 加载按钮
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                        [_tableView reloadData];
                        
                    }
                }else{
                    if (listArr && [listArr count] == [kPageSize integerValue] && [dic[@"size"] integerValue] >=_currentPage*10)
                    {
                        _currentPage ++ ;//有下一页  show 加载按钮
                        [_tableArray addObjectsFromArray:listArr];
                        [_tableView reloadData];
                    }
                    else if ([listArr count] == 0)
                    {
                        //没有下一页  hide 加载按钮
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                        [_tableView reloadData];
                        
                    }
                    else if ([listArr count] < [kPageSize integerValue] && [dic[@"size"] integerValue] >=(_currentPage-1)*10)
                    {
                        _currentPage ++ ;
                        [_tableArray addObjectsFromArray:listArr];
                        [_tableView reloadData];
                    }
                }
            }

        }

    }];
}

#pragma mark - Notification
- (void)getNotification:(NSNotification *)notification
{
    NSInteger seletIndex = [notification.userInfo[KwNotificationInfoKey_Index] integerValue];
    _currtenNum = seletIndex;
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return  0.0000001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"ActiveApplyCell";
    ActiveApplyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell)
    {
        cell = [[ActiveApplyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    switch (self.moduleType) {
        case HomeModuleTypeSA:
        case HomeModuleTypeSC:{
            cell.model = _tableArray[indexPath.row];
        }
            break;
        case HomeModuleTypePA:
        case HomeModuleTypePC: {
            cell.proDisModel = _tableArray[indexPath.row];
        }
            break;
        case HomeModuleTypeEA:
        case HomeModuleTypeEC: {
            cell.ECModel = _tableArray[indexPath.row];
        }
            break;
        case HomeModuleTypeOA:
        case HomeModuleTypeOC: {
            cell.OCModel = _tableArray[indexPath.row];
        }
            break;
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SAListModel *model = _tableArray[indexPath.row];
    switch (self.moduleType) {
        case HomeModuleTypeSA:
        case HomeModuleTypeSC:{
            //促销详情
            ActiviteDetailVC *detaliVC = [[ActiviteDetailVC alloc] init];
            detaliVC.orderId = model.id;
            detaliVC.moduleType = _moduleType;
            [self.navigationController pushViewController:detaliVC animated:YES];
        }
            break;
        case HomeModuleTypePA:
        case HomeModuleTypePC: {
            ProductDisplayDetailVC *detaliVC = [[ProductDisplayDetailVC alloc] init];
            detaliVC.orderId = model.id;
            detaliVC.moduleType = _moduleType;
            [self.navigationController pushViewController:detaliVC animated:YES];
        }
            break;
        case HomeModuleTypeEA:
        case HomeModuleTypeEC: {
            EnterCostDetailVC *detaliVC = [[EnterCostDetailVC alloc] init];
            detaliVC.orderId = model.id;
            detaliVC.moduleType = _moduleType;
            [self.navigationController pushViewController:detaliVC animated:YES];
        }
            break;
        case HomeModuleTypeOA:
        case HomeModuleTypeOC: {
            OtherCostDetailVC *detaliVC = [[OtherCostDetailVC alloc] init];
            detaliVC.orderId = model.id;
            detaliVC.moduleType = _moduleType;
            [self.navigationController pushViewController:detaliVC animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - event response
- (void)changeList
{
    if (_segCtr.selectedSegmentIndex == 1)
    {
        _confirmBtn.hidden = YES;
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make    ) {
            make.bottom.equalTo(@0);
        }];
    }
    else
    {
        _confirmBtn.hidden = NO;
        [_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency) {
                make.bottom.equalTo(@-55);
            } else {
                make.bottom.equalTo(@0);
            }
        }];
    }
    _currentPage = 1;
    _currtenNum = 0;
    KwSegViewHelper *kwHelper = [[KwSegViewHelper alloc] init];
    kwHelper.kwSegIndex = 0;
    [self.tableView.mj_header beginRefreshing];
}

//申请
- (void)startPlaceAnOrder
{
    if (_moduleType == HomeModuleTypeSA)
    {
        ActiviteApplyVC *vc =[[ActiviteApplyVC alloc] init];
        vc.isChangeInfo = NO;
        vc.isSubmit = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (_moduleType == HomeModuleTypePA)
    {
        PDCommitVC *vc = [[PDCommitVC alloc] init];
        vc.isChangeInfo = NO;
        vc.isSubmit = YES;
        vc.moduleType = _moduleType;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (_moduleType == HomeModuleTypeEA)
    {
        EnterCostCommitVC *vc = [[EnterCostCommitVC alloc] init];
        vc.isChangeInfo = NO;
        vc.isSubmit = YES;
        vc.moduleType = _moduleType;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (_moduleType == HomeModuleTypeOA)
    {
        OtherCostCommitVC *vc = [[OtherCostCommitVC alloc] init];
        vc.isChangeInfo = NO;
        vc.isSubmit = YES;
        vc.moduleType = _moduleType;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - private method
- (void)stopRefresh {
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma mark - getter and setter
- (NSArray *)titleArr {
    if (!_titleArr) {
        if ([[Singleton shareInstance].userType integerValue] == UserTypeAgency) {
            _titleArr = @[@"全部",@"审批中",@"审批完成",@"已拒绝"];
        } else {
            _titleArr = @[@"全部",@"审批中",@"待我审批",@"审批完成",@"已拒绝"];
        }
    }
    return _titleArr;
}

@end
